import { useClipboard } from '@vueuse/core'
import { message } from 'ant-design-vue'
import { defineComponent, provide, ref } from 'vue'
import CellConfig from './components/CellConfig'
import FlowConfig from './components/FlowConfig'
import { createFlowState, flowStateKey } from './hooks/useFlowState'
import useGraph from './hooks/useGraph'

export default defineComponent({
  name: 'SpsFlowDesign',
  setup () {
    const flowState = createFlowState()
    const {
      stencilContanerRef,
      graphContanerRef,
      graphToJson,
      updateCell
    } = useGraph(flowState)
    provide(flowStateKey, flowState)
    // #region Json 对话框
    const modalVisible = ref(false)
    const jsonStr = ref('')
    const { copy } = useClipboard()
    const modalShow = () => {
      modalVisible.value = true
      jsonStr.value = JSON.stringify(graphToJson(), null, 2)
    }
    const copyJson = async () => {
      await copy(jsonStr.value)
      message.success('已复制到粘贴板')
    }
    // #endregion
    return () => {
      return (<>
        <a-layout class="sps-flow-design h-full w-full">
          {/* 标题与工具栏 */}
          <a-layout-header class="flex">
            <div class="flex-1">Sps-Flow-Design</div>
            <div>
              <a-button onClick={ modalShow }>Json</a-button>
            </div>
          </a-layout-header>
          {/* 设计器主体 */}
          <a-layout>
            <a-layout-content class="flex">
              {/* 左侧节点库 */}
              <div ref={ stencilContanerRef } class="w-60 h-full relative border-r-2 border-gray-300"></div>
              {/* 流程面板 */}
              <div ref={ graphContanerRef } class="h-full flex-1" style={{ height: '100%' }}></div>
            </a-layout-content>
            {/* 右侧配置 */}
            <a-layout-sider width={ 300 }>
              {
                //@ts-ignore
                flowState.currentCell ? <CellConfig onSubmit={ updateCell } /> : <FlowConfig />
              }
            </a-layout-sider>
          </a-layout>
        </a-layout>
        <a-modal
          v-model={[modalVisible.value, 'visible']}
          title="Json"
          cancelText="关闭"
          okText="复制"
          onOk={ copyJson }>
          <div class="h-96 overflow-y-auto">
            <pre>{ jsonStr.value }</pre>
          </div>
        </a-modal>
      </>)
    }
  }
})
